var app = sm("do_App");
var page = sm("do_Page");
var nf = sm("do_Notification");
var hashdata = mm("do_HashData");
var deviceone = require("deviceone");
var http = require("helper/http");
var httpSilence = require("helper/httpSilence");
var imgTool = require("helper/picture");
var helperOpen = require("helper/open");
var mallUrl = require("url/mall");

var createProductUrl = mallUrl.url.product.doAdd;//发布商品

// UI
var headerAout = ui("headerAout");
var aLayoutRoot = ui("aLayoutRoot");
var root = ui("$");
var shopId = null;//店铺id
var isRecommend = 2;
var moneyFix =  /^[0-9]*(\.[0-9]{1,2})?$/;

page.on("loaded", function(data) {
	shopId = page.getData().shopId;
	initCategory4Product();//初始化商品一级分类
});
var textResume = ui("textResume");
// 加载头部
var addheader = headerAout.add("header", "source://view/reuse/header.ui", 0, 0);
ui(addheader+".labelTitle").text = "发布商品";
// andriod返回键
page.on("back", function() {
	app.closePage();
});
// 左上角-返回
var headerLeft = ui(addheader + ".headerLeft");
headerLeft.on("touch", function() {
	app.closePage()
});
var layoutMain = ui("do_LinearLayout_main");
/*商品名称*/
var addNameText = layoutMain.add("nameText", "source://view/reuse/form/mutiInput.ui",0,0);
var nameText = ui("nameText");
nameText.bindData(hashdata);
hashdata.addData({
    "textTitle" : "商品名称",
    "hint":"请输入商品名称"
});
nameText.refreshData();
var textName = ui(addNameText+".textInput");

/*类别*/
var categoryId = null;
var categoryName = null;
//初始化商品一级分类
var levle1List4Product = null;
function initCategory4Product(){
	httpSilence.post(mallUrl.url.category.firstLevel, {}, function(data) {
		levle1List4Product = data.categoryList;
	})
}

var addCategoryPicker = root.add("typeList","source://view/qshop/manage/product/category.ui",0,0);
ui("aLayoutCategory").on("touch","",300,function(){
	page.hideKeyboard();
	if(levle1List4Product!=null && levle1List4Product.length>0){
		page.fire("categoryList",levle1List4Product);
		page.fire("categorys","true");
	}
});


page.on("refreshCategory4Product",function(data){
	var typeCategoryStr = ui("labelCategory");
	if(data){
		if(data.sid != null){//如果有二级分类
			categoryId = data.sid;
			categoryName = data.sname;
			typeCategoryStr.text = data.bname + " / " + data.sname;
		}else if(data.bid != null){//如果只有一级分类
			categoryId = data.bid;
			categoryName = data.bname;
			typeCategoryStr.text = data.bname;
		}else{
			categoryId = null;
			categoryName = '';
			typeCategoryStr.text = '';
		}
	}else{
		categoryId = null;
		categoryName = '';
		typeCategoryStr.text = '';
	}
});
/***********选择分类end**************/
var layoutSection = ui("layoutSection");

/*计量单位*/
var addUnitText = layoutSection.add("unitText", "source://view/reuse/form/mutiInput.ui",0,0);
var unitText = ui("unitText");
unitText.bindData(hashdata);
hashdata.addData({
    "textTitle" : "计量单位",
    "hint":"如：个、打",
    "inputType": "ASC"
});
unitText.refreshData();
var textUnit = ui(addUnitText+".textInput");
/*品牌*/
var addBrandNameText = layoutSection.add("brandNameText", "source://view/reuse/form/mutiInput.ui","unitText");
var brandNameText = ui("brandNameText");
brandNameText.bindData(hashdata);
hashdata.addData({
    "textTitle" : "品牌",
    "hint":"请输入商品品牌",
    "inputType": "ASC"
});
brandNameText.refreshData();
var textBrandName = ui(addBrandNameText+".textInput");

/** **************点击-添加规格***************/
var lineLayout=ui("linearLayoutSpec");
var aLayoutAdd = ui("aLayoutAdd");

var index = 0;
var specMaxCount = 5;
var addCell0 = lineLayout.add("myCell0", "source://view/qshop/manage/product/specCell.ui");
ui(addCell0+".btnDelte").visible = false;
//添加cell
aLayoutAdd.on("touch","",300,function(data, e){
	var cellIdsList = lineLayout.getChildren();
	if(cellIdsList.length >= specMaxCount){
		nf.alert("最多添加5个规格");
		return;
	}
	var flag = false;
	for(var i in cellIdsList){
		var labelSpec = ui(cellIdsList[i]+".textFieldSpecName");
		var labelPrice = ui(cellIdsList[i]+".textFieldPrice");
		var labelOprice = ui(cellIdsList[i]+".textFieldMarketPrice");
		var labeLinventory = ui(cellIdsList[i]+".textFieldStock");
		if(labelSpec.text==""||labelPrice.text==""||labelOprice.text==""||labeLinventory.text==""){
			flag = true;
			break;
		}
	}
	if(flag){
		nf.toast("规格信息不完整");
		return;
	};
	var lastCellId = "";
	lastCellId = cellIdsList[cellIdsList.length-1];//取最后一个cell的id作为下一个添加的cell起点，这样就不会插到前面去
	index ++;
	var curIndex = index;
	var addCell = lineLayout.add("myCell"+curIndex, "source://view/qshop/manage/product/specCell.ui",lastCellId);
	ui(addCell+".btnDelte").on("touch", "", 300, function(data){
		ui("myCell"+curIndex).remove();//删除自身
		lineLayout.redraw();
	})
});

/** **************点击-添加规格-end*****************/


/** 是否推荐 **/
var swIsRecommend = [ 0, " ", " " ]; // 0:开关状态 1:关闭状态文字 2:开启状态文字
var switchIsRecommend = layoutSection.add("isRecommend","source://view/reuse/form/mutiSwitch.ui","brandNameText");
var ui_isRecommend = ui("isRecommend");
var labelTitle_isRecommend = ui(switchIsRecommend + ".labelTitle");
var aLayoutRoot_isRecommend = ui(switchIsRecommend + ".aLayoutRoot");
aLayoutRoot_isRecommend.tag=1;
ui_isRecommend.bindData(hashdata);
hashdata.addData({
	"labelTitle" : "是否推荐"
})
ui_isRecommend.refreshData();
ui_isRecommend.on("switchtag", function(data) {
	if (data == 0) {// 关闭，不允许别人查看
		isRecommend = 2;
	}
	if (data == 1) {// 打开，允许别人查看、默认是打开
		isRecommend = 1;
	}
});
ui_isRecommend.fire("switchzt", swIsRecommend);
/** 是否推荐（完） **/
/** **************点击-添加商品封面图片-begin***************/
var imgCoverMaxCount = 5;//最多上传5张封面
var imgGrid1 = ui("imgGridCover");
var listdataImg1 = mm("do_ListData");
imgGrid1.bindItems(listdataImg1);

ui("aLayoutImgCover").on("touch", function(data, e) {
	var lessImgCount = imgCoverMaxCount-listdataImg1.getCount();
	if(lessImgCount<=0){
		nf.toast("最多只能上传"+imgCoverMaxCount+"张图片.");
		return;
	}
	imgTool.imgMulti(lessImgCount, selectImgBack1);
});
function selectImgBack1(imgList) {
	listdataImg1.addData(imgList.map(function(path) {
		return {
			"imgPath" : path
		}
	}));
	imgGrid1.refreshItems();
}
imgGrid1.on("touch", function(data, e) {
	listdataImg1.removeData([ data ]);
	imgGrid1.refreshItems();
});
/** **************点击-添加商品封面图片-end*****************/

/** **************点击-添加商品详情图片-begin***************/
var imgResumeMaxCount = 5;//最多上传5张详情图片
var imgGrid2 = ui("imgGridResume");
var listdataImg2 = mm("do_ListData");
imgGrid2.bindItems(listdataImg2);

ui("aLayoutImgResume").on("touch", function(data, e) {
	var lessImgCount = imgResumeMaxCount-listdataImg2.getCount();
	if(lessImgCount<=0){
		nf.toast("最多只能上传"+imgResumeMaxCount+"张图片.");
		return;
	}
	imgTool.imgMulti(lessImgCount, selectImgBack2);
});
function selectImgBack2(imgList) {
	listdataImg2.addData(imgList.map(function(path) {
		return {
			"imgPath" : path
		}
	}));
	imgGrid2.refreshItems();
}
imgGrid2.on("touch", function(data, e) {
	listdataImg2.removeData([ data ]);
	imgGrid2.refreshItems();
});
/** **************点击-添加商品详情图片-end*****************/


/*************选择成色begin**************/
var isAllNew = 1;//是否全新的:1-是;2-否
var radioItem=[ui("imgAllNew"),ui("imgSecondHand")]
ui("layOutAllNew").on("touch",function(data,e){//点击【全新】
	checkRadio(0);
	isAllNew = 1;
})
ui("layOutSecondHand").on("touch",function(data,e){//点击【二手】
	checkRadio(1);
	isAllNew = 2;
})

function checkRadio(index){
	for (var i = 0; i < radioItem.length; i++) {
		if(i==index){
			radioItem[i].source="source://image/common/radiocheck.png";
		}else{
			radioItem[i].source="source://image/common/radio.png";
		}
	}
}
/************选择成色end***************/

ui("btnAdd").on("touch", "", 5000, function() {
	createProduct();
})
function createProduct() {
	page.hideKeyboard();
	var productName = textName.text;//商品名称
	var resume = textResume.text;//描述
	var unit = textUnit.text;
	var brandName = textBrandName.text;//品牌名称
	
	if (productName == '' || productName == null) {
		nf.toast("亲，请输入商品名称。");
		return;
	}
	if (resume == '' || resume == null) {
		nf.toast("亲，请填写商品描述。");
		return;
	}
	if (categoryId == '' || categoryId == null) {
		nf.toast("亲，请选择商品分类。");
		return;
	}
	if (unit == '' || unit == null) {
		nf.toast("亲，请填写计量单位。");
		return;
	}
	if (listdataImg1.getCount() == 0) {
		nf.toast("亲，请添加商品封面图片。");
		return;
	}
	if (listdataImg2.getCount() == 0) {
		nf.toast("亲，请添加商品详情图片。");
		return;
	}
	if(shopId == ''){
		nf.toast("店铺id为空。");
		return;
	}
	
	var imgFiles = [];
	var coverImgLen = listdataImg1.getCount();//封面图片数量
	for (var i = 0; i < listdataImg1.getCount(); i++) {
		imgFiles.push(listdataImg1.getOne(i).imgPath);
	}
	for (var i = 0; i < listdataImg2.getCount(); i++) {
		imgFiles.push(listdataImg2.getOne(i).imgPath);
	}
	if (imgFiles.length > 0) {
		http.form(imgFiles, "mall", function(imgDatas) {
			var string4imgs = imgDatas.path;// 返回图片云端路径（后部份）用分号隔开
			var imgs=string4imgs.split(";");
			var imgFiles4Cover = [];//封面-图片列表
			var imgFiles4Resume = [];//详情-图片列表
			for (var i = 0; i < imgs.length; i++) {
				if(i < coverImgLen){
					imgFiles4Cover.push(imgs[i]);
				}else{
					imgFiles4Resume.push(imgs[i]);
				}
			}
			
			var params = {
				"shopId" : shopId,
				"name" : productName,
				"resume" : resume,
				"categoryId" : categoryId,
				"brandName" : brandName,
				"resumeImg" : imgFiles4Resume.join(";"),
				"img" : imgFiles4Cover.join(";"),
				"unit" : unit,
				"isAllNew" : isAllNew,
				"feature" : "" ,//商品特色描述
				"isRecommend" : isRecommend
			};
			
			//规格数据
			var cellIdsList = lineLayout.getChildren();
			var flag = false;
			var htmlJson = [];
			for(var i in cellIdsList){
                var labelSpec = ui(cellIdsList[i]+".textFieldSpecName");
				var labelPrice = ui(cellIdsList[i]+".textFieldPrice");
				var labelOprice = ui(cellIdsList[i]+".textFieldMarketPrice");
				var labeLinventory = ui(cellIdsList[i]+".textFieldStock");
				if(labelSpec.text==""||labelPrice.text==""||labelOprice.text==""||labeLinventory.text==""){
					flag = true;
					break;
				}
				else{
					htmlJson.push({"specName":labelSpec.text,"price":labelPrice.text,"marketPrice":labelOprice.text,"stock":labeLinventory.text});
				}
				if(!moneyFix.test(labelPrice.text)){
					nf.toast("请输入正确的商品价格（保留两位小数）");
					return;
				}
				if(!moneyFix.test(labelOprice.text)){
					nf.toast("请输入正确的商品原价（保留两位小数）");
					return;
				}
				var ckNum = /^[0-9]*[1-9][0-9]*$/;
				
				if(!ckNum.test(labeLinventory.text)){
					nf.toast("请输入正确的库存");
					return;
				}
			}
			if(flag){
				nf.toast("规格信息不完整");
				return;
			};
			
			if(htmlJson.length > 0){
				params.productSpecLst = htmlJson;
			}else{
				nf.toast("商品规格信息不为空");
				return;
			}
			httpSilence.post(createProductUrl, params, function(data) {
				nf.toast("发布成功");
				app.closePage({mall_add_product:true});
			});
		});
	} 
}

//点击背景隐藏输入键盘
root.on("touch",function(){
	page.hideKeyboard();
})